//
//  GRAddDevice.m
//  Smart
//
//  Created by XJYMAC on 16/11/2.
//  Copyright © 2016年 Gree Inc. All rights reserved.
//

#import "GRConfigManager.h"
#import "AppDelegate.h"
#import "GRAddShowSuccessDeviceViewController.h"
#import "GRChooseDeviceViewController.h"
#import <GRSocketFramework/GRSocketFramework.h>
#import <GRSocketFramework/GRUdpSendPacket.h>

//杭州古北
#import "NetworkAPI.h"

@interface GRConfigManager()


@property(nonatomic,strong) GRUdpSendPacket *socketSend;

@property(nonatomic,strong) GRUdpReceivePacket *socketReveive;

/**发包数据*/
@property(nonatomic,strong)NSData *data;

@property(nonatomic,copy)GRConfigResultBlock configResultBlock;

@property(nonatomic,strong)NSTimer *tenChangeTime;

@end

extern deviceType devicetype;

@implementation GRConfigManager
{
    BOOL configSwitch;//高通 no 结束发包 yes 一直发包
    NSInteger tenChangeTimeBool; //1 发江波龙  2发古北
    LTLink  *mlink;
    NSDictionary *_dict;
    NSInteger macCount;
    NetworkAPI *api;
    dispatch_queue_t queue;
}


-(void)dealloc {
    
    GRLog(@"%s",__func__);

    GRLog(@"1234567345678");

}

- (instancetype)init
{
    if (self = [super init]) {
        _socketSend = [[GRUdpSendPacket alloc] init];
        mlink = [[LTLink alloc] init];
        _macArray = [NSMutableArray array];
        api = [[NetworkAPI alloc] init];
        queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

    

- (void)startConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord  configTime:(CGFloat)configTime configResultBlock:(GRConfigResultBlock)configResultBlock
{
    _socketReveive = [[GRUdpReceivePacket alloc] initWithDelegate:self];
    [self.socketReveive bindToPort:8001 error:nil];
    [self.socketReveive receiveWithTimeOut:120.0f];;
        
    NSString *configDisHost = [GRUserManager getDisServer];
    NSString *hostStr = configDisHost;
    if (hostStr.length > 12) {
        hostStr = [hostStr substringToIndex:2];
    }else
    {
        hostStr = @"";//空字符串代表中国
    }
    
    NSString *PASSWORD = passWord;
    PASSWORD = [NSString stringWithFormat:@"%@+%@",PASSWORD,hostStr];
    
    
    if (devicetype == deviceTypeBusinessAirContionter) {
        
        [self startGreeConfigWthSSID:SSID passWord:passWord configDisHost:configDisHost];
        [self startBroadLickConfigWithSSID:SSID passWord:passWord gatewayaddr:nil];
        
    }else{
        

        [self startBroadLickConfigWithSSID:SSID passWord:passWord gatewayaddr:nil];
        [NSThread sleepForTimeInterval:0.3];
        [self pushOrStartBroadLink];//关闭古北
        
        //开启格力配网
        [self startGreeConfigWthSSID:SSID passWord:passWord configDisHost:configDisHost];
        //开启江波龙配网
        [mlink startLinkWithSSID:SSID password:PASSWORD secureKey:nil];//开启江波龙
        //开启定时器 (每隔3秒发一次古北配网)
        _tenChangeTime = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(tenChangeTimeClick) userInfo:nil repeats:YES];
        tenChangeTimeBool = 1;
    }
    _configResultBlock = [configResultBlock copy];
}

- (void)tenChangeTimeClick
{
    if (tenChangeTimeBool == 1) {
        
        tenChangeTimeBool = 2;
        [self pushOrStartBroadLink];//开启古北
        
    }else if (tenChangeTimeBool == 2){
        
        tenChangeTimeBool = 1;
        [self pushOrStartBroadLink];//关闭古北
    }
}


#pragma mark -开启古北配网
- (void)startBroadLickConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord gatewayaddr:(NSString *)gatewayaddr
{
    
    GR_WeakSelf
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary *dic = nil;
        //商用空调
        if (devicetype == deviceTypeBusinessAirContionter) {
            
            dic = [[NSDictionary alloc] initWithObjectsAndKeys:SSID, @"ssid", passWord, @"password",@(2),@"cfgversion",@(120),@"timeout",@(5400),@"senddelay", nil];
            
        }else{
            
             dic = [[NSDictionary alloc] initWithObjectsAndKeys:SSID, @"ssid", passWord, @"password",@(3),@"cfgversion",@(120),@"timeout",@(5400),@"senddelay", nil];//1800
        }
        
        NSData *descData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *easyconfigResult = [api deviceEasyConfig:[[NSString alloc] initWithData:descData encoding:NSUTF8StringEncoding]];
        
        
        
        GRLog(@"easyconfigResult: %@", easyconfigResult);
        
        NSDictionary *dict =  [easyconfigResult JSONValue];
        
        [weakSelf didReceiveFromBroadLick:dict];
        
        GRLog(@"dict = %@",dict);
    });
}

- (void)pushOrStartBroadLink
{
    
    __weak NetworkAPI * m_api= api;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [m_api deviceEasyConfigPauseOrRestart];
    });
}


#pragma mark - 接收古北配网成功信息
- (void)didReceiveFromBroadLick:(NSDictionary *)dict
{
    if ([[dict objectForKey:@"msg"] isEqualToString:@"success"]) {
        
        NSMutableDictionary *mutabDict = [NSMutableDictionary dictionaryWithDictionary:dict];
        mutabDict[@"t"] = @"configok";
        mutabDict[@"r"] = @(200);
        NSString *deviceName = [mutabDict safeObjectForKey:@"mac"];
        deviceName = [deviceName stringByReplacingOccurrencesOfString:@":" withString:@""];
        mutabDict[@"mac"] = deviceName;
        mutabDict[@"devaddr"] = [mutabDict safeObjectForKey:@"devaddr"];
        [self receiveWithDict:mutabDict];
    }
}




//开启格力配网
- (void)startGreeConfigWthSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
{

    GR_WeakSelf
    configSwitch = YES;
    dispatch_async(queue, ^{
        while (configSwitch) {
            
            [weakSelf onekeyConfigWithSSID:SSID passWord:passWord configDisHost:configDisHost];
        }
    });
}

- (void)didReceive:(NSData *)data fromHost:(NSString *)host port:(UInt16)port
{
    
    //监听一直都在,在5秒结束后设置_configmonitorOver = yes ,120秒结束监听失败,返回失败.
    if (!_configmonitorOver) {
        
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [string JSONValue];
        
        //记录配网成功设备的数量-避免相同的设备重复统计
        if (_macArray.count > 0) {
            
            for (NSDictionary *macDict in _macArray) {
                
                if ([macDict isEqualToDictionary:dict]) {
                    
                    return;
                }
            }
        }
        
        [self receiveWithDict:dict];
    }
    
}

- (void)receiveWithDict:(NSDictionary *)dict
{
    [_macArray addSafeObject:dict];
    [self stopConfig];
    GRLog(@"_macArray= %@",_macArray);
    //这里用block把通知发送出去
    _configResultBlock(dict);
}

#pragma mark - 结束配网
- (void)stopConfig
{
    configSwitch = NO;
    _configmonitorOver = YES;
    if (_socketSend) {
        
        [_socketSend close];
        _socketSend = nil;
    }
    if (_socketReveive) {
        [_socketReveive stopListen];
        [_socketReveive close];
        _socketReveive = nil;
    }
    [api deviceEasyConfigCancel];
    [mlink stopLink];
    if (_tenChangeTime) {
        
        [_tenChangeTime invalidate];
        _tenChangeTime = nil;
    }
}

- (void)onekeyConfigWithSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
{
    if (!_socketSend) return;
    
    static NSString *str = nil;
    NSString *hostStr = configDisHost;
    NSString *ssid = SSID;
    NSString *password = passWord;
    password = [NSString stringWithFormat:@"%@+%@",password,hostStr];
    //    NSData *data = [self jsonDataWithSSID:SSID passWord:passWord configDisHost:configDisHost];
    NSString *dataString = @"1";//这个数字是随便填的,data数据多导致路由器缓存太多,配网速度大大下降,所以越少越好.
    NSData *data = [dataString JSONData];
    
    static NSInteger  integer;
    
    int j = 0;
    int k = 0;
    for (int i = 0; i < 120; i++) {
        
        [NSThread sleepForTimeInterval:0.02];//0.02  50包  0.012 70包
        integer = 0;
        if (i == 3) {
            integer = 120;
        }
        if (i <= (4 + ssid.length -1)  && i > 3 ) {
            NSString *wifiStr =  [ssid substringWithRange:NSMakeRange(j, 1)];
            integer = [wifiStr characterAtIndex:0];
            
            j++;
            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
            if (!_socketSend) return;
            [_socketSend sendData:data toHost:str port:9957];
            
            
        }else if (i > 35 && i <= (36 + password.length - 1))
        {
            NSString *passwordStr = [password substringWithRange:NSMakeRange(k, 1)];
            integer = [passwordStr characterAtIndex:0];
            k++;
            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
            if (!_socketSend) return;
            [_socketSend sendData:data toHost:str port:9957];
            
        }else
        {
            str = [NSString stringWithFormat:@"239.%d.%zd.254",i,integer];
            if (!_socketSend) return;
            [_socketSend sendData:data toHost:str port:9957];
        }
    }
}

- (NSData *)jsonDataWithSSID:(NSString *)SSID passWord:(NSString *)passWord configDisHost:(NSString *)configDisHost
{
    
    if (_data == nil) {
        
        NSString *hostStr = configDisHost;
        
        NSString *ssid = SSID;
        NSString *password = passWord;
        password = [NSString stringWithFormat:@"%@+%@",password,hostStr];
        
        
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:120];
        
        static NSInteger  integerrrr;
        int a = 0;
        int b = 0;
        for (int i = 0; i < 120; i++) {
            
            
            integerrrr = 0;
            if (i == 3) {
                integerrrr = 120;
                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
            }
            else if (i <= (4 + ssid.length -1)  && i > 3 ) {
                NSString *wifiStr =  [ssid substringWithRange:NSMakeRange(a, 1)];
                integerrrr = [wifiStr characterAtIndex:0];
                a++;
                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
                
            }else if (i > 35 && i <= (36 + password.length - 1))
            {
                NSString *passwordStr = [password substringWithRange:NSMakeRange(b, 1)];
                integerrrr = [passwordStr characterAtIndex:0];
                
                b++;
                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
            }else{
                
                [mutableArray addSafeObject:[NSString stringWithFormat:@"%zd",integerrrr]];
            }
            
        }
        
        NSData *data = [mutableArray JSONData];
        return data;
    }
    return _data;
}

@end
